package org.jupiter.blog.service.config;

import org.jupiter.blog.api.http.JupiterResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public JupiterResult<Void> handleValidException(MethodArgumentNotValidException ex) {
		String msg = Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage();
		return JupiterResult.fail(msg);
	}

	@ExceptionHandler(BindException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public JupiterResult<Void> handleBindException(BindException ex) {
		String msg = Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage();
		return JupiterResult.fail(msg);
	}

	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public JupiterResult<Void> handleException(Exception ex) {
		return JupiterResult.fail("系统错误：" + ex.getMessage());
	}
}
